/*
 * @description:
 * @Author: lal
 * @Date: 2020-05-26 16:39:44
 * @LastEditors: lal
 * @LastEditTime: 2020-07-23 09:30:50
 */

const { ipcMain, BrowserWindow, dialog, shell, app } = require("electron");
const log = require("electron-log");
import fs from "fs";
import { createWindow, windows } from "../windows/create-window";
import { createNotification } from "../native-ui/notice";
import path from "path";
import checkForUpdates from "../update/checkUpdate";
import "../native-ui/dialogs/index";
// import windowInstance from "./BrowserWindowInstance";
//  进程通讯

ipcMain.on("dbValue", function(e, val) {
  // log.info(val * val);
  //e 默认是事件
  let calcVal = val * val;
  // e.reply("dbValueDone", calcVal);
  // event.sender.send();

  // 返回键名
  // windows.
  // Object.value(windows);

  for (var i in windows) {
    windows[i].webContents.send("dbValueDone", calcVal);
  }
  // for (let item of windows.keys()) {
  //   item.webContents.send("dbValueDone", calcVal);
  // }
});

ipcMain.handle("dbValue", (e, val) => {
  return val * val;
});

ipcMain.handle("notice", (e, val) => {
  createNotification({
    title: val,
    body: val,
  });
  return "通知完成";
});
ipcMain.handle("render2-process", () => {
  return "render2-process通信完成";
});

ipcMain.handle("newWin", (event, opts = {}) => {
  if (opts && opts.parent) {
    opts.parent = BrowserWindow.getFocusedWindow();
  } else {
    opts.parent = null;
  }

  createWindow("newWindow", opts, "http://localhost:8082/index.html#/");

  log.info(Object.keys(windows).length);
  return "createWindowDone";
});

// 主进程监听渲染进程传来的信息
ipcMain.on("update", async () => {
  console.log("update");
  log.info("update");
  // checkForUpdates();
  let dest = path.join(__dirname, "electron-demo Setup 0.1.0.exe");
  log.info(dest);
  log.info(shell);
  await shell.openPath(dest); // 打开下载好的安装程序
  // app.quit(); // 退出当前客户端
  app.exit();
});
/**
 * 渲染进程请求选择保存结果的目录
 */
ipcMain.on("IPC_EXPORT", async (event, { name, value }) => {
  const window = BrowserWindow.getFocusedWindow();
  const result = await dialog.showSaveDialog(window, {
    defaultPath: name,
  });
  if (result.canceled === false) {
    await fs.writeFileSync(result.filePath, new Uint8Array(Buffer.from(value)));
  }
});
